<!--
 * @Author: TANGB02 13233582+Ace-Tang@user.noreply.gitee.com
 * @Date: 2024-01-29 14:40:25
 * @LastEditors: TANGB02 13233582+Ace-Tang@user.noreply.gitee.com
 * @LastEditTime: 2024-02-26 10:48:37
 * @FilePath: \ycq\ycq\ycq1.0\src\components\canvas\verificationCode.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="img-verify">
    <canvas
      ref="verify"
      style="width: 120px; height: 40px"
      @click="handleDraw"
    ></canvas>
  </div>
</template>

<script type="text/ecmascript-6" setup>
import { onMounted, reactive, ref, defineEmits } from 'vue'
//验证码变量
let txt = ref("")
const emits = defineEmits(["handleTxt"])

 const verify = ref(null)
    const state = reactive({
      pool: 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789', // 字符串
      width: 120, // canvas宽
      height: 40, // canvas高
    })
    onMounted(() => {
      // 初始化绘制图片验证码
          draw()
    })

    // 点击图片重新绘制
    const handleDraw = () => {
       draw()
    }

    // 随机数
    const randomNum = (min, max) => {
      return parseInt(Math.random() * (max - min) + min)
    }
    // 随机颜色
    const randomColor = (min, max) => {
      const r = randomNum(min, max)
      const g = randomNum(min, max)
      const b = randomNum(min, max)
      return `rgb(${r},${g},${b})`
    }

    // 绘制图片
    const draw = () => {
      const ctx = verify.value.getContext('2d')
      // 填充颜色
      ctx.fillStyle = randomColor(180, 230)
      // 填充的位置
      ctx.fillRect(0, 0, 300, 150)
      // 随机产生字符串，并且随机旋转
      for (let i = 0; i < 4; i++) {
        // 随机的一个字符
        const text = state.pool[randomNum(0, state.pool.length)]
        //暂存验证码
        txt.value += text
        // 随机的字体大小
        const fontSize = randomNum(65, 90)
        // 字体随机的旋转角度
        const deg = randomNum(-30, 30)
        ctx.font = fontSize + 'px Simhei'
        ctx.textBaseline = 'top'
        ctx.fillStyle = randomColor(80, 150)
        ctx.save()
        ctx.translate(50 * i + 15, 15)
        ctx.rotate((deg * Math.PI) / 180)
        ctx.fillText(text, 50, 37)
        ctx.restore()
      }
      // 传送验证码给父组件
      emits("handleTxt", txt.value)
      txt.value = ""
}
defineExpose({
  draw
})
</script>
<style type="text/css" scoped>
.img-verify canvas {
  cursor: pointer;
}
</style>
